/* This file computes asymptotic variances for the estimation of the asymptotic
SD of the BLUE RD estimator (piecewise quintic regressions). After running the
regression, compute sigma^2 (X'X)^-1. Also include that quantity times n.
*/

clear
set more off

cap log close
log using "${logs}/asymptotic_variances_rdd.log", replace


* Create dataset with plotted SD information
gen filename = ""
gen asymp_var_rd_est = .
gen asymp_var_rd_n_est = .
gen sd = .

save "${dat}/asymptotic_variances_rdd.dta", replace

foreach rng in 1 {
   
	foreach paper in "ADGP1" "BDGP2" "CDGP3" "DDGP4" "EDGP5" "FDGP6" ///
		"GDGP7" "HDGP8" "IDGP9" "JDGP10" "KDGP11" {
	
		use "${dat}/DGP/`paper'_Coefficients.dta", replace
		
		scalar res_sd = res_std_global in 1
		scalar n = N_global in 1
      
		foreach filejump in 0 {
      
			use "${sim_dat}/`paper'_`filejump'_`rng'", clear
			
			keep y x
      
			gen filename = "`paper'_`filejump'_yesline_nofit_smallbinwidth_normalscale_`rng'_qs"
			gen asymp_var_rd_est = .
			gen asymp_var_rd_n_est = .
			gen sd = res_sd
      
			* Generate regressors for piecewise quintic RDD
			gen x2 = x*x
			gen x3 = x*x*x
			gen x4 = x*x*x*x
			gen x5 = x*x*x*x*x
			gen D = x >= 0
			gen Dx = D * x
			gen Dx2 = D * x2
			gen Dx3 = D * x3
			gen Dx4 = D * x4
			gen Dx5 = D * x5
			
			reg y x x2 x3 x4 x5 D Dx Dx2 Dx3 Dx4 Dx5
			
			* Get X'X
			matrix accum XX = x x2 x3 x4 x5 D Dx Dx2 Dx3 Dx4 Dx5
			matrix XX = invsym(XX)
			
			* Extract asymptotic variance
			matrix asymp_var = res_sd^2 * XX
			matrix asymp_var = asymp_var["D", "D"]
			matrix asymp_var_n = n * asymp_var
			
			replace asymp_var_rd_est = asymp_var[1, 1]
			replace asymp_var_rd_n_est = asymp_var_n[1, 1]
      
			keep filename asymp_var_rd* sd
			gen se_ratio = sqrt(asymp_var_rd_est) / sd
			keep if _n == 1

      
			replace filename = subinstr(filename, "_qs", "_es", .)

			append using "${dat}/asymptotic_variances_rdd.dta"
			save "${dat}/asymptotic_variances_rdd.dta", replace
		}
	}
}

label var filename "File name for corresponding dataset"
label var asymp_var_rd_est "Asymptotic variance of the BLUE RD estimator (piecewise quintic regressions); sigma^2 (X'X)^-1"
label var asymp_var_rd_n_est "asymp_var_rd_est * n"
label var sd "DGP standard deviation"
label var se_ratio "sqrt(asymp_var_rd_est) / sd"

save "${dat}/asymptotic_variances_rdd.dta", replace